package com.fare.taluo.action.system.register;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.openkoala.auth.application.RoleApplication;
import org.openkoala.auth.application.UserApplication;
import org.openkoala.auth.application.vo.RoleVO;
import org.openkoala.auth.application.vo.UserVO;
import org.openkoala.koala.auth.ss3adapter.CustomUserDetails;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.system.auth.UserInfoApplication;
import com.fare.taluo.application.system.register.RegistercodeApplication;
import com.fare.taluo.auth.security.LogonUserCertificate;
import com.fare.taluo.base.struts2.json.BaseJsonStrutsAction;
import com.fare.taluo.base.struts2.json.JsonReturnBean;
import com.fare.taluo.util.I18nUtil;
import com.fare.taluo.util.param.ParamUtils;
import com.fare.taluo.vo.auth.RegisterVo;
import com.fare.taluo.vo.core.SourceEntityVO;
import com.fare.taluo.vo.registercode.RegisterCodeVO;

@Controller("registerAction")
@Scope("prototype")
@Namespace("/register")
public class RegisterAction extends BaseJsonStrutsAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2773834788291265041L;

	private String invitationAler;
	{
		Locale locale = super.getLocale();
		invitationAler=I18nUtil.getProperties(locale).get("register.invitatioCodeDon'tPass");
	}
	
	@Inject
	private RoleApplication roleApplication;

	private List<RoleVO> roleList;
	
	private String hbaseKey;	
	
	private String codes;

	private List<SourceEntityVO> sourceList;
	
	private RegisterVo registerVo;
	
	public RegisterVo getRegisterVo() {
		return registerVo;
	}

	public void setRegisterVo(RegisterVo registerVo) {
		this.registerVo = registerVo;
	}

	public List<SourceEntityVO> getSourceList() {
		return sourceList;
	}

	public List<RoleVO> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<RoleVO> roleList) {
		this.roleList = roleList;
	}

	public String getHbaseKey() {
		return hbaseKey;
	}

	public void setHbaseKey(String hbaseKey) {
		this.hbaseKey = hbaseKey;
	}

	public String getCodes() {
		return codes;
	}

	public void setCodes(String codes) {
		this.codes = codes;
	}

	@Action(value = "input", results = {@Result(name = "success", type="dispatcher", location="/pages/system/register/register.jsp") })
	public String input() throws Exception {
		String invitationCode = ParamUtils.getParameter(request, "code");
			List<RoleVO> roles = roleApplication.findAllRole();
			roleList = new ArrayList<RoleVO>();
			 Locale locale = super.getLocale();
			for (RoleVO vo : roles) {
				if ("收益管理员".equals(vo.getName())) {
					if(locale.toString().equalsIgnoreCase("en_US")){
						vo.setName("RevenueManager");
					}
					roleList.add(vo);
				} else if ("渠道管理员".equals(vo.getName())) {
					if(locale.toString().equalsIgnoreCase("en_US")){
						vo.setName("ChannelManager");
					}
					roleList.add(vo);
				}
			}
			//设置登陆信息
			SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
					new CustomUserDetails("shenhang01",
					"shenhang01",true,true,true,true,null),null));
		sourceList = InstanceFactory.getInstance(SourceApplication.class).findCrawlAirCompanys();
		I18nUtil.sourceConvert2I18N(sourceList, super.getLocale());
		//TODO 这里将邀请码加密后解密出来
		request.setAttribute("invitationCode", invitationCode);
		return SUCCESS;
	}

	/**
	 * 注册
	 * */
	@Action(value = "register", results = {@Result(name = "success", type="json", params={"root","returnBean"}) })
	public String register() {
		UserInfoApplication userInfoApplication = InstanceFactory.getInstance(UserInfoApplication.class);
		RegistercodeApplication registercodeApplication = InstanceFactory.getInstance(RegistercodeApplication.class);
		returnBean = new JsonReturnBean();
		String hbaseKeys=null;
		String code=null;
		try {
			hbaseKeys = URLDecoder.decode(hbaseKey,"utf-8");
			code=URLDecoder.decode(codes,"utf-8");
		} catch (Exception e) {
		}
		try {
			if(hbaseKeys !=null && !"".equals(hbaseKeys)){
				registerVo.setSourceId(hbaseKeys);
			}
			if(code !=null && !"".equals(code)){
				registerVo.setInvitationCode(code);
			}
			List<RegisterCodeVO> list = registercodeApplication.checkCode(registerVo.getInvitationCode(), registerVo.getSourceId());
			if(list==null || list.isEmpty()){
				returnBean.setHasOk(false);
				returnBean.setMessage(invitationAler);
			}else{
				userInfoApplication.save(registerVo);
				//设置登陆信息
				SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
						new CustomUserDetails(registerVo.getPassword(),
						registerVo.getUserName(),true,true,true,true,null),null));
				//进行到此表示，注册用户已经插入数据库，设置当前用户session
				request.getSession().setAttribute("currentUser", null);
				returnBean.setHasOk(true);
				returnBean.setBean(registerVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnBean.setHasOk(false);
			returnBean.setMessage(e.getMessage());
		}
		return SUCCESS;
	}
	/**
	 * 检查userName是否已注册
	 * */
	@Action(value = "checkUserName", results = {@Result(name = "success", type="json", params={"root","returnBean"}) })
	public String checkUserName() throws Exception {
		returnBean = new JsonReturnBean();
		try{
			String userName = ParamUtils.getParameter(request, "registerVo.userName");
			UserVO user = InstanceFactory.getInstance(UserApplication.class).findByUserAccount(userName);
			if(user != null){
				returnBean.setHasOk(true);
			}else{
				returnBean.setHasOk(false);
			}
		}catch(Exception e){
			e.printStackTrace();
			returnBean.setHasOk(false);
		}
		return SUCCESS;
	}
}
